import os
import simplejson
from django.shortcuts import render
from django.http import HttpResponse
from util.jiafu_log import JiaFuLogger
from django.contrib.auth.decorators import login_required
from django.contrib.auth import authenticate, login, logout
from django.views.decorators.csrf import csrf_exempt
# Create your views here.

logger = JiaFuLogger("jiafu_server:bitmex:view")


def error_rsp(code, message):
    """错误的响应
    """
    return HttpResponse(simplejson.dumps({
        "errno": code,
        "message": message
    }), content_type='application/json')


@login_required
def get_api_key(request):
    user = request.user
    if request.method == 'GET':
        if user.account:
            return HttpResponse(content=simplejson.dumps({'api_key': user.account.api_key,
                                                          'api_secret': user.account.api_secret,
                                                          'is_testnet': user.account.is_testnet}))
        else:
            return HttpResponse(status=404, content=simplejson.dumps({'msg': '当前交易账户未关联BitMex账号'}))


@csrf_exempt
def login_view(request):
    """登录视图
    """
    name = request.POST.get('name', '')
    password = request.POST.get('password', '')
    if '' in (name, password):
        return error_rsp(5001, '缺少用户名或密码')
    user = authenticate(name=name, password=password)
    if not user:
        return error_rsp(5002, '用户名或密码错误, 或已被禁用')
    if not user.account:
        return error_rsp(5003, '用户未关联交易帐号，不允许登录')
    login(request, user)
    return HttpResponse(content=simplejson.dumps({'msg': "ok"}))


@csrf_exempt
@login_required
def logout_view(request):
    """退出系统
    """
    logout(request)
    return HttpResponse(content=simplejson.dumps({'msg': "ok"}))
